package com.example.adapter.apply;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class DispatchServlet {
    private List<HandlerAdapter> handlerAdapters;

    public DispatchServlet() {
        initHandlerAdapters();
    }

    private void initHandlerAdapters() {
        handlerAdapters = new ArrayList<>();
        handlerAdapters.add(new HttpRequestHandlerAdapter());
        handlerAdapters.add(new RequestMappingHandlerAdapter());
    }

    public void dispatch(Object paramType) {
        Object req = new Object(), resp = new Object(), params = new Object[2];

        HandlerAdapter handlerAdapter = this.getHandler(paramType);
        Object result = handlerAdapter.handle(req, resp, params);
    }

    private HandlerAdapter getHandler(Object paramType) {
        Iterator<HandlerAdapter> it = handlerAdapters.iterator();
        while (it.hasNext()) {
            HandlerAdapter adapter = it.next();
            if (adapter.support(paramType)) {
                return adapter;
            }
        }
        throw new RuntimeException("No adapter could handle the paramType: " + paramType);
    }
}
